package paytreasure.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import paytreasure.dao.ConsumeDao;
import paytreasure.po.Consume;
import paytreasure.service.ConsumeService;
import paytreasure.util.ConstantUtil;
import paytreasure.vo.ResultVo;


public class ConsumeServiceImpl implements ConsumeService{
	
	@Autowired
	private ConsumeDao consumeDao;
	
	private ResultVo result;
    /**
     * 插入新的消费记录
     */
	public ResultVo insertConsume(Consume consume) {
		
		if(consume.getCreateDate()==null){
			return new ResultVo(ConstantUtil.RESULT_ERROR, "添加失败！");
		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
		String monthDate = sdf.format(consume.getCreateDate());
		int count = consumeDao.getCount(monthDate);
		if(count > 0) {
			//查询已添加月份
			List<String> month = consumeDao.queryAllMonth();
			String string = "";
			for (String str : month) {
				string += str + ",";
			}
			string = string.substring(0,string.length()-1);
			result = new ResultVo(ConstantUtil.RESULT_SUCCESS, "当前已添加",string);
			return result;
		}
		
		int d = consumeDao.addConsume(consume);
		if(d == 0){
			result = new ResultVo(ConstantUtil.RESULT_ERROR, "添加失败！");
			return result;
		}
		result = new ResultVo(ConstantUtil.RESULT_SUCCESS, "保存成功！");
		return result;
	}
	

	/**
	 * 
	 * 根据相应的ID查询消费记录
	 */
	public ResultVo getConsumeById(String id) {
		
		Consume consume = consumeDao.getConsumeById(id);

		Double sum =  Double.valueOf(consume.getShopping())
					+ Double.valueOf(consume.getBelow())
					+ Double.valueOf(consume.getPayConsume()) +
					+ Double.valueOf(consume.getTelConsume()) +
					+ Double.valueOf(consume.getOther());
		Double conSum = Double.valueOf(consume.getConsume());
		//如果总消费与和不同时
		if(sum != conSum){
			consume.setConsume(String.valueOf(sum));
		}

		if(consume == null) {
			result = new ResultVo(ConstantUtil.RESULT_ERROR, "未获取到数据");
		}
		result = new ResultVo(ConstantUtil.RESULT_SUCCESS, "查询成功！",consume);
		return result;
	}

	/**
	 * 
	 * 根据对应的id修改消费信息
	 */
	public ResultVo updateConsume(Consume con) {
		
		int d = consumeDao.updateConsume(con);
		ResultVo result = new ResultVo();
	    if(d > 0){  
	    	result.isResultSuccess();
	    	result.setResultMsg("修改成功");
	    }else{ 
	    	result.isResultError();
	    	result.setResultMsg("修改失败");
	    }  
	    return result;
	}
}
